using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Program14
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();//构造一个用于序列化操作的对象
            p.Name = "传智播客";
            p.Age = 8;
            //构造序列化器对象
            BinaryFormatter bf = new BinaryFormatter();
            //构造输出流
            using (FileStream fs = new FileStream("Data.txt",
                FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //进行序列化输出操作
                bf.Serialize(fs, p);
                Console.WriteLine("序列化操作成功，对象已写入文件");
            }
            using (FileStream fs1 = new FileStream("Data.txt",
                FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //进行反序列化，返回一个object类型的对象
                object obj = bf.Deserialize(fs1);
                Console.WriteLine("反序列化对象数据为" + obj);
            }
            Console.ReadKey();
        }
        [Serializable] //使用Serializable标签标记Person类
        public class Person
        {
            public int Age
            {
                get;
                set;
            }
            public string Name
            {
                get;
                set;
            }
            public override string ToString()
            {
                return string.Format("Name:{0},Age:{1}", this.Name,
                                                                       this.Age);
            }
        }
    }
}
